# -*- coding: utf-8 -*-
from typing import List
import pymysql
from conf.read_conf import *


def pytest_collection_modifyitems(
        session: "Session", config: "Config", items: List["Item"]
) -> None:
    for item in items:
        item.name = item.name.encode("utf-8").decode("unicode-escape")
        item._nodeid = item.nodeid.encode("utf-8").decode("unicode-escape")


def execute_sql(sql):
    """
    执行 SQL 语句。
    :param sql: 要执行的 SQL 语句。
    :return: None（通常我们不需要从执行 SQL 的函数中返回结果，除非有特定的需求）
    """
    # 连接到数据库
    # 如果web端口是28081，那么mysql端口就用53306，否则就用端口+2
    if int(read_conf(envs_test, 'port')) == 28081:
        port = int("53306")
    else:
        port = int(read_conf(envs_test, 'port')) + 2
    connection = pymysql.connect(host=read_conf(envs_test, 'ip'),
                                 port=port,
                                 user=read_conf(envs_test, 'mysql_user'),
                                 password=read_conf(envs_test, 'mysql_password'),
                                 database=read_conf(envs_test, 'mysql_db'),
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)
    try:
        with connection.cursor() as cursor:
            print(f"Executing SQL: {sql}")  # 打印执行的 SQL 语句
            cursor.execute(sql)
            # 检查 SQL 是否是 SELECT 语句，并据此获取结果
            if sql.upper().startswith('SELECT'):
                results = cursor.fetchall()
                print(f"Affected rows (for SELECT): {cursor.rowcount}")  # 对于 SELECT，rowcount 可能不准确
            else:
                # 对于 INSERT、UPDATE、DELETE 等语句
                connection.commit()
                print(f"Affected rows: {cursor.rowcount}")  # 打印被影响的行数
                results = None

    finally:
        connection.close()

    return results


# 执行sql文件
def execute_sqlfile(file_path):
    # file_path = f"C:/Users/Administrator/Desktop/d/sql.sql"
    with open(file_path, 'r', encoding='utf-8') as file:
        sql_commands = file.read()
        # 分割SQL语句，假设每个语句以分号结束
        sqls = [command.strip() for command in sql_commands.split(';') if command.strip() != '']
        for sql in sqls:
            execute_sql(sql)
